package com.assets.Check;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.assets.CanniBalize.NewCheck_allot;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.Check.newTanWanCheck.NewCheck_alter;
import com.assets.Ip_set.Url;
import com.assets.Maintain.Maintain_data;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.bean.Input_item1;
import com.assets.bean.Issued_bean;
import com.assets.newNHF.util.LogUtils;
import com.assets.room.database.MyDataBase;
import com.assets.room.entity.Asset;
import com.assets.room.entity.CheckData;
import com.assets.util.IdWorkerUtil;
import com.assets.util.MyOkHttp;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;
import com.hb.dialog.myDialog.MyAlertInputDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/22.
 *
 *
 * 盘点页面  有读卡页面
 *
 */

public class Check extends BaseActivity1 {

    private static final String TAG = "我爱你";
    private String checkDetailIds, isEdit = "";//单号，状态
    private RecyclerView recyclerView;
    private Button scan, submit;//扫码，上传,rfid
    private String id;
    private Button add_remark;
    private String query_url = "http://" + Url.IP + "/api/checkAssetScanQuery";
    private LoadingDialog loadingDialog;
    private List<String> assetNumbers = new ArrayList<>();
    private String url = "http://" + Url.IP + "/api/checkdetailQueryByIds";
    private String upload_url = "http://" + Url.IP + "/api/assetCheck";
    private String add_br = "http://" + Url.IP + "/api/checkTextAdd";
    private List<Input_item1> For_data = new ArrayList<>();
    private List<Input_item1> Have_data = new ArrayList<>();
    private List<Input_item1> profit_data = new ArrayList<>();
    private List<Input_item1> losses_data = new ArrayList<>();
    private List<Input_item1> dataList = new ArrayList<>();
    private CheckAdapter adapter = new CheckAdapter(dataList);
    private EditText et_num;


    private TextView odd, createuser, sum, createdate, date;//盘点单号，创建人，应盘总数，创建日期，完成日期
    private TextView For_inventory, Have_inventory, inventory_profit, inventory_losses;//待盘点，已盘点，盘盈，盘亏
    private int star = 0;
    private String deptId = "";
    /*private Handler handler = new Handler();
    private Runnable runnable = () -> {
        adapter_item.notifyDataSetChanged();
        Have_inventory.setText(String.valueOf(Have_data.size()));
        For_inventory.setText(String.valueOf(For_data.size()));
        inventory_profit.setText(String.valueOf(profit_data.size()));
        inventory_losses.setText(String.valueOf(losses_data.size()));
    };*/

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.check_main);
        deptId = getIntent().getStringExtra("createDate");
        LogUtils.d("createDate" + deptId);
        initView();
//        loadData();
        setData();
        initRFID();
        add_remark.setOnClickListener(v -> {
            MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Check.this).builder()
                    .setTitle("请填写备注")
                    .setEditText("");
            myAlertInputDialog.setPositiveButton("确认", v12 -> {
                add_remarks(myAlertInputDialog.getResult());
                myAlertInputDialog.dismiss();
            }).setNegativeButton("取消", v1 -> myAlertInputDialog.dismiss());
            myAlertInputDialog.show();
        });
        scan.setOnClickListener(v -> {
            startQrCode();
            LogUtils.d("调用扫码");
        });
        submit.setOnClickListener(v -> new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Check.this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {

                String thisStatus = MyDataBase.init(Check.this).checkDao().getStatusByCheckId(odd.getText().toString());
                if (thisStatus.equals("2")) {
                    showToast("当前任务已提交!");
                    return;
                }

                //取消：position=-1,确定 position=0
                if (position == 0) {
//                    showDialog("正在上传");
//                    upload();
                    /**
                     * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
                     */

                    int weiNum = MyDataBase.init(Check.this).checkDataDao().getCheckByResult("3",odd.getText().toString()).size();
                    MyDataBase.init(Check.this).checkDataDao().updateByIdLoss("2","1", "3", odd.getText().toString());

                    int yesNum = MyDataBase.init(Check.this).checkDataDao().getCheckByResult("1",odd.getText().toString()).size();
                    int yiNum = MyDataBase.init(Check.this).checkDataDao().getCheckByResult("0",odd.getText().toString()).size();
                    int lossNum = MyDataBase.init(Check.this).checkDataDao().getCheckByResult("2",odd.getText().toString()).size();
//                    int goNum = (weiNum - yiNum);
                    Log.d("xxxx=====", "最后提交亏数量: " + lossNum);
                    inventory_losses.setText(lossNum+ "");
                    inventory_profit.setText(yesNum + "");
                    For_inventory.setText("0");
                    Have_inventory.setText("" + yiNum);


                    for (int i = 0; i < For_data.size(); i++) {

                        CheckData checkDataById1 = MyDataBase.init(Check.this).checkDataDao().getCheckDataById(For_data.get(i).getCode_number(), odd.getText().toString());
                        if (checkDataById1.getCheckResult().equals("2")) {
                            For_data.remove(i);
                        }

                    }

                    runOnUiThread(() -> {
                        dataList.clear();
                        dataList.addAll(For_data);
                        adapter.notifyDataSetChanged();
                    });

                    showToast("提交成功");

                    MyDataBase.init(Check.this).checkDao().updateStatus("2", odd.getText().toString());
                    Date nowTime = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                    MyDataBase.init(Check.this).checkDao().updateSubmitTime(sdf.format(nowTime), "1", odd.getText().toString());
                    date.setText("".equals(MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()))&&MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()) == null ? "" : MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()));
//                    Map<String, Object> map1 = new HashMap();
//
//                    map1.put("assetList" , MyOkHttp.getInstance().getGson().toJson(MyDataBase.init(Check.this).checkDataDao().getAllCheckData()));
//
//
//                    MyDataBase.init(Check.this).checkDao().updateStatus("2", odd.getText().toString());
//                    Log.d("这个Map是什么", "map: " + map1);
                }
            }
        }).setCancelable(true).show());
    }


    private void upload() {
        String assetNumbersToString = assetNumbers.toString();
        Map<String, String> map = new HashMap<>();
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("checkId", id);
        map.put("deptId", deptId);
        map.put("assetNumbers", assetNumbersToString.substring(1, assetNumbersToString.length() - 1));
        MyOkHttp.getInstance().post(upload_url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
                showToast("连接服务器失败");
            }

            @Override
            public void requestComplete() {
                canDialog();
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                final String responseData = response.body().string();
                LogUtils.d(responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        showToast("提交成功");
                        finish();
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    showToast("数据解析异常");
                    e.printStackTrace();
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void setData() {

        List<CheckData> allAssetCheckData = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("3", Long.valueOf(odd.getText().toString()));
        Log.d(TAG, "查到的数据: " + new Gson().toJson(allAssetCheckData));
//        * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
        //待盘点的数量
        For_inventory.setText(MyDataBase.init(this)
                .checkDataDao().
                getAssetCheckByStatus("3",
                        Long.valueOf(odd.getText().toString())).size() + "");
        //已经盘点的数量
        Have_inventory.setText(MyDataBase.init(this).checkDataDao()
                .getAssetCheckByStatus("0",
                        Long.valueOf(odd.getText().toString())).size() + "");
        //盘盈的数量
        inventory_profit.setText(MyDataBase.init(this).checkDataDao()
                .getAssetCheckByStatus("1",
                        Long.valueOf(odd.getText().toString())).size() + "");
        //盘亏的数量
        inventory_losses.setText(MyDataBase.init(this)
                .checkDataDao().getAssetCheckByStatus("2",
                        Long.valueOf(odd.getText().toString())).size() + "");

        for (int i = 0; i < allAssetCheckData.size(); i++) {
            String assetName = allAssetCheckData.get(i).getAssetName();
            //提醒宇锟修改
//            String deptId = allAssetCheckData.get(i).getDept();
            String assetNumber = allAssetCheckData.get(i).getAssetNumber();
//            String userId = allAssetCheckData.get(i).getUser();
            String model = allAssetCheckData.get(i).getModel();
            String place = allAssetCheckData.get(i).getPlace();
//            String rfid = allAssetCheckData.get(i).getRfid();
//            String image = allAssetCheckData.get(i).getImage();
//            if (!TextUtils.isEmpty(image)) {
//                image = "http://" + Url.IP + image;
//            }
            For_data.add(new Input_item1("", assetName, deptId, assetNumber, "", model,  MyDataBase.init(Check.this).placeDao().getNameById(place), ""));
        }
        runOnUiThread(() -> {
            dataList.clear();
            dataList.addAll(For_data);
            adapter.notifyDataSetChanged();
//            loadingDialog.dismiss();
        });
    }

    private void loadData() {
        Map<String, String> map = new HashMap<>();
        map.put("checkDetailIds", checkDetailIds.substring(1, checkDetailIds.length() - 1));
        LogUtils.d(checkDetailIds.substring(1, checkDetailIds.length() - 1));
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                showToast("请连接网络后重试");
            }

            @Override
            public void requestComplete() {
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                LogUtils.d(responseData);
                try {
                    JSONObject jsonObject = new JSONObject(responseData);
                    String createUser = jsonObject.getString("createuser");
                    String sum1 = jsonObject.getString("sum");
                    String createDate = jsonObject.getString("createdate");
                    String date1 = jsonObject.getString("date");
                    String num1 = jsonObject.getString("num1");
                    String num2 = jsonObject.getString("num2");
                    String num3 = jsonObject.getString("num3");
                    String num4 = jsonObject.getString("num4");
                    runOnUiThread(() -> {
                        createuser.setText(createUser);
                        sum.setText(sum1);
                        if (TextUtils.isEmpty(createDate)) {
                            createdate.setText(createDate);
                        } else {
                            createdate.setText(createDate.substring(0, 10));
                        }
                        date.setText(date1);
                        For_inventory.setText(num1);
                        Have_inventory.setText(num2);
                        inventory_profit.setText(num3);
                        inventory_losses.setText(num4);
                    });
                    JSONArray jsonArray1 = jsonObject.getJSONArray("assets1");//待
                    JSONArray jsonArray2 = jsonObject.getJSONArray("assets2");//已
                    JSONArray jsonArray3 = jsonObject.getJSONArray("assets3");//盘盈
                    JSONArray jsonArray4 = jsonObject.getJSONArray("assets4");//盘亏
                    if (!jsonArray1.equals("[]")) {
                        Gson gson = new Gson();
                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonArray1), new TypeToken<List<Issued_bean>>() {
                        }.getType());
                        for (int i = 0; i < userList.size(); i++) {
                            String assetName = userList.get(i).getAssetName();
                            //提醒宇锟修改
                            String deptId = userList.get(i).getDept();
                            String assetNumber = userList.get(i).getAssetNumber();
                            String userId = userList.get(i).getUser();
                            String model = userList.get(i).getModel();
                            String place = userList.get(i).getPlace();
                            String rfid = userList.get(i).getRfid();
                            String image = userList.get(i).getImage();
                            if (!TextUtils.isEmpty(image)) {
                                image = "http://" + Url.IP + image;
                            }
                            For_data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, place, rfid));
                        }
                    }
                    if (!jsonArray2.equals("[]")) {
                        Gson gson = new Gson();
                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonArray2), new TypeToken<List<Issued_bean>>() {
                        }.getType());
                        for (int i = 0; i < userList.size(); i++) {
                            String assetName = userList.get(i).getAssetName();
                            String dept = userList.get(i).getDept();
                            String assetNumber = userList.get(i).getAssetNumber();
                            String userId = userList.get(i).getUser();
                            String model = userList.get(i).getModel();
                            String place = userList.get(i).getPlace();
                            String image = userList.get(i).getImage();
                            if (!TextUtils.isEmpty(image)) {
                                image = "http://" + Url.IP + image;
                            }
                            Have_data.add(new Input_item1(image, assetName, dept, assetNumber, userId, model, place, ""));
                        }
                    }
                    if (!jsonArray3.equals("[]")) {
                        Gson gson = new Gson();
                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonArray3), new TypeToken<List<Issued_bean>>() {
                        }.getType());
                        for (int i = 0; i < userList.size(); i++) {
                            String assetName = userList.get(i).getAssetName();
                            String dept = userList.get(i).getDept();
                            String assetNumber = userList.get(i).getAssetNumber();
                            String userId = userList.get(i).getUser();
                            String model = userList.get(i).getModel();
                            String place = userList.get(i).getPlace();
                            String rfid = userList.get(i).getRfid();
                            String image = userList.get(i).getImage();
                            if (!TextUtils.isEmpty(image)) {
                                image = "http://" + Url.IP + image;
                            }
                            profit_data.add(new Input_item1(image, assetName, dept, assetNumber, userId, model, place, rfid));
                        }
                    }
                    if (!jsonArray4.equals("[]")) {
                        Gson gson = new Gson();
                        List<Issued_bean> userList = gson.fromJson(String.valueOf(jsonArray4), new TypeToken<List<Issued_bean>>() {
                        }.getType());
                        for (int i = 0; i < userList.size(); i++) {
                            String assetName = userList.get(i).getAssetName();
                            String dept = userList.get(i).getDept();
                            String assetNumber = userList.get(i).getAssetNumber();
                            String userId = userList.get(i).getUser();
                            String model = userList.get(i).getModel();
                            String place = userList.get(i).getPlace();
                            String rfid = userList.get(i).getRfid();
                            String image = userList.get(i).getImage();
                            if (!TextUtils.isEmpty(image)) {
                                image = "http://" + Url.IP + image;
                            }
                            losses_data.add(new Input_item1(image, assetName, dept, assetNumber, userId, model, place, rfid));
                        }
                    }
                    runOnUiThread(() -> {
                        dataList.clear();
                        dataList.addAll(For_data);
                        adapter.notifyDataSetChanged();
                        loadingDialog.dismiss();
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void initView() {
//        loadingDialog = new LoadingDialog(this);
//        loadingDialog.setMessage("加载中....");
//        loadingDialog.show();
        et_num = (EditText) findViewById(R.id.et_num);
        add_remark = (Button) findViewById(R.id.add);
        recyclerView = (RecyclerView) findViewById(R.id.fragment2_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        //待盘点，已盘点，盘盈，盘亏
        LinearLayout losses = (LinearLayout) findViewById(R.id.losses);
        LinearLayout profit = (LinearLayout) findViewById(R.id.profit);
        LinearLayout aFor = (LinearLayout) findViewById(R.id.For);
        LinearLayout have = (LinearLayout) findViewById(R.id.Have);
        ImageView imageView = (ImageView) findViewById(R.id.fh);
        imageView.setOnClickListener(v -> {
            finish();
        });
        Intent intent = getIntent();
        checkDetailIds = intent.getStringExtra("checkId");
        isEdit = intent.getStringExtra("isEdit");
        LogUtils.d("checkId" + checkDetailIds);
        id = intent.getStringExtra("id");
        scan = (Button) findViewById(R.id.scan);
        submit = (Button) findViewById(R.id.submit);
        odd = (TextView) findViewById(R.id.odd);
        odd.setText(intent.getStringExtra("id"));
        createuser = (TextView) findViewById(R.id.createuser);
        createuser.setText(intent.getStringExtra("createUser"));
        sum = (TextView) findViewById(R.id.sum);
        sum.setText(intent.getStringExtra("checkNum"));
        createdate = (TextView) findViewById(R.id.createdate);
        createdate.setText(intent.getStringExtra("createDate"));
        date = (TextView) findViewById(R.id.date);
        For_inventory = (TextView) findViewById(R.id.For_inventory);
        For_inventory.setTextColor(Color.parseColor("#00FF00"));
        et_num.setFocusableInTouchMode(true);
        date.setText("".equals(MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()))&&MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()) == null ? "" : MyDataBase.init(Check.this).checkDao().getSubmitTime(odd.getText().toString()));
        et_num.requestFocus();
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String scanData = et_num.getText().toString();
                if (TextUtils.isEmpty(scanData)) {
                    return;
                }
                et_num.selectAll();
                handleScanData(scanData);
            }
        });
        //待盘点的点击方法
        aFor.setOnClickListener(v -> {
            star = 0;
            For_inventory.setTextColor(Color.parseColor("#00FF00"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));
            dataList.clear();
            For_data.clear();
            /**
             * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
             */
            List<CheckData> checkByResult = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("3", Long.valueOf(odd.getText().toString()));
            for (int i = 0; i < checkByResult.size(); i++) {

                For_data.add(new Input_item1("", checkByResult.get(i).getAssetName(), deptId,
                        checkByResult.get(i).getAssetNumber(), "", checkByResult.get(i).getModel(),
                        MyDataBase.init(Check.this).placeDao().getNameById(checkByResult.get(i).getPlace()), ""));

            }

            dataList.addAll(For_data);
            adapter.notifyDataSetChanged();
        });
        //已经盘点
        Have_inventory = (TextView) findViewById(R.id.Have_inventory);
        have.setOnClickListener(v -> {
            Log.d(TAG, "Have_data: " + Have_data);
            star = 1;
            Have_inventory.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));
            Have_data.clear();
            dataList.clear();
            /**
             * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
             */
            List<CheckData> checkByResult = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("0", Long.valueOf(odd.getText().toString()));
            for (int i = 0; i < checkByResult.size(); i++) {

                Have_data.add(new Input_item1("", checkByResult.get(i).getAssetName(), deptId,
                        checkByResult.get(i).getAssetNumber(), "", checkByResult.get(i).getModel(),
                        MyDataBase.init(Check.this).placeDao().getNameById(checkByResult.get(i).getPlace()), ""));

            }

            dataList.addAll(Have_data);
            adapter.notifyDataSetChanged();
        });
        //盘盈
        inventory_profit = (TextView) findViewById(R.id.inventory_profit);
        profit.setOnClickListener(v -> {
            star = 2;
            inventory_profit.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_losses.setTextColor(Color.parseColor("#FF0000"));
            dataList.clear();
            profit_data.clear();

            /**
             * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
             */
            List<CheckData> checkByResult = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("1", Long.valueOf(odd.getText().toString()));
            for (int i = 0; i < checkByResult.size(); i++) {

                profit_data.add(new Input_item1("", checkByResult.get(i).getAssetName(), deptId,
                        checkByResult.get(i).getAssetNumber(), "", checkByResult.get(i).getModel(),
                        MyDataBase.init(Check.this).placeDao().getNameById(checkByResult.get(i).getPlace()), ""));

            }

            dataList.addAll(profit_data);
            adapter.notifyDataSetChanged();
        });
        inventory_losses = (TextView) findViewById(R.id.inventory_losses);
        losses.setOnClickListener(v -> {
            star = 3;
            inventory_losses.setTextColor(Color.parseColor("#00FF00"));
            For_inventory.setTextColor(Color.parseColor("#000000"));
            Have_inventory.setTextColor(Color.parseColor("#000000"));
            inventory_profit.setTextColor(Color.parseColor("#3794fc"));
            dataList.clear();
            losses_data.clear();
            /**
             * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
             */
            List<CheckData> checkByResult = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("2", Long.valueOf(odd.getText().toString()));
            for (int i = 0; i < checkByResult.size(); i++) {

                losses_data.add(new Input_item1("", checkByResult.get(i).getAssetName(), deptId,
                        checkByResult.get(i).getAssetNumber(), "", checkByResult.get(i).getModel(),
                        MyDataBase.init(Check.this).placeDao().getNameById(checkByResult.get(i).getPlace()), ""));

            }

            dataList.addAll(losses_data);
            adapter.notifyDataSetChanged();
        });
        adapter.setRequestSuccess((position)->{
            String assetNumber = dataList.get(position).getCode_number();
            Log.d("setRequestSuccess==","id="+id+",code_number="+assetNumber);
            Intent intent1 = new Intent(Check.this, Maintain_data.class);
            intent1.putExtra("checkId",id);
            intent1.putExtra("assetNumber",assetNumber);
            //   intent1.putExtra("taskPointContentId",taskPointContentId);
            startActivityForResult(intent1,8);
        });
        adapter.setOnClick(position -> {
            if (!TextUtils.isEmpty(isEdit)) {
                //showToast("闲置资产无法转移");
                if (star == 1) {
                    Intent intent1 = new Intent(Check.this, NewCheck_allot.class);
                    intent1.putExtra("AssetName", Have_data.get(position).getAsset_name());
                    intent1.putExtra("AssetNumber", Have_data.get(position).getCode_number());
                    LogUtils.d("AssetName" + Have_data.get(position).getAsset_name());
                    LogUtils.d("AssetNumber" + Have_data.get(position).getCode_number());
                    startActivityForResult(intent1, 1);
                }
                if (star == 2) {
                    Intent intent1 = new Intent(Check.this, NewCheck_allot.class);
                    intent1.putExtra("status", "1");
                    intent1.putExtra("AssetName", profit_data.get(position).getAsset_name());
                    intent1.putExtra("AssetNumber", profit_data.get(position).getCode_number());
                    LogUtils.d("AssetName" + profit_data.get(position).getAsset_name());
                    LogUtils.d("AssetNumber" + profit_data.get(position).getCode_number());
                    startActivityForResult(intent1, 2);
                }
                return;
            }
            if (star == 1) {
                Intent intent1 = new Intent(Check.this, NewCheck_alter.class);
                intent1.putExtra("AssetName", Have_data.get(position).getAsset_name());
                intent1.putExtra("AssetNumber", Have_data.get(position).getCode_number());
                LogUtils.d("AssetName" + Have_data.get(position).getAsset_name());
                LogUtils.d("AssetNumber" + Have_data.get(position).getCode_number());
                startActivityForResult(intent1, 1);
            }
            if (star == 2) {
                Intent intent1 = new Intent(Check.this, NewCheck_alter.class);
                intent1.putExtra("status", "1");
                intent1.putExtra("AssetName", profit_data.get(position).getAsset_name());
                intent1.putExtra("AssetNumber", profit_data.get(position).getCode_number());
                LogUtils.d("AssetName" + profit_data.get(position).getAsset_name());
                LogUtils.d("AssetNumber" + profit_data.get(position).getCode_number());
                startActivityForResult(intent1, 2);
            }
        });
    }

    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Check.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Check.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Check.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Check.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            handleScanData(scanResult);
        }
        if (requestCode == 2 && resultCode == 6) {
            for (int i = 0; i < profit_data.size(); i++) {
                if (profit_data.get(i).getCode_number().equals(data.getExtras().getString("AssetNumber")))
                    profit_data.get(i).setCustodian(data.getExtras().getString("preserver"));
                profit_data.get(i).setSection(data.getExtras().getString("DeptId"));
                profit_data.get(i).setCategory(data.getExtras().getString("place"));
                if (star == 2) {
                    adapter.notifyItemChanged(i);
                }
            }
        }
        if (requestCode == 1 && resultCode == 6) {
            for (int i = 0; i < Have_data.size(); i++) {
                if (Have_data.get(i).getCode_number().equals(data.getExtras().getString("AssetNumber")))
                    Have_data.get(i).setCustodian(data.getExtras().getString("preserver"));
                Have_data.get(i).setSection(data.getExtras().getString("DeptId"));
                Have_data.get(i).setCategory(data.getExtras().getString("place"));
                if (star == 1) {
                    adapter.notifyItemChanged(i);
                }
            }
        }
    }

    private void query(final String assetNumber, final String RFID) {
        Map<String, String> map = new HashMap<>();
        map.put("assetNumber", assetNumber);
        map.put("rfid", RFID);
        map.put("checkdetailIds", checkDetailIds);
        Log.d("epc====","query="+map.toString());
        MyOkHttp.getInstance().post(query_url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
                showToast("连接服务器失败");
                if (!TextUtils.isEmpty(RFID)) {
                    Check.this.map.remove(RFID);
                }
            }

            @Override
            public void requestComplete() {
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                LogUtils.d(RFID + responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        JSONObject jsonObject = json.getJSONObject("asset");
                        String assetName = jsonObject.getString("assetName");
                        String deptId = jsonObject.getString("deptId");
                        String assetNumber = jsonObject.getString("assetNumber");
                        String userId = jsonObject.getString("userId");
                        String model = jsonObject.getString("model");
                        String type = jsonObject.getString("type");
                        String rfid = jsonObject.getString("rfid");
                        String image = jsonObject.getString("image");
                        if (!TextUtils.isEmpty(image)) {
                            image = "http://" + Url.IP + image;
                        }
                        if (assetNumbers.contains(assetNumber)) return;
                        assetNumbers.add(assetNumber);
                        profit_data.add(new Input_item1(image, assetName, deptId, assetNumber, userId, model, type, rfid));
                        Log.d("profit_data==","profit_data="+profit_data.size()+",profit="+profit_data+",star="+star);
                        if (star == 2) {
                            Log.d("profit_data==","111");
                            runOnUiThread(() -> {
                                adapter.notifyItemInserted(adapter.getItemCount() - 1);
                                Have_inventory.setText(String.valueOf(Have_data.size()));
                                For_inventory.setText(String.valueOf(For_data.size()));
                                inventory_profit.setText(String.valueOf(profit_data.size()));
                                inventory_losses.setText(String.valueOf(losses_data.size()));
                            });
                        }
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                    if (json.getString("state").equals("2")) {
                        showToast("资产不存在");
                    }
                    if (json.getString("state").equals("3")) {
                        showToast("资产待报废");
                    }
                    if (json.getString("state").equals("4")) {
                        showToast("资产未入库");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void add_remarks(final String remark) {
        Map<String, String> map = new HashMap<>();
        map.put("text", remark);
        map.put("checkId", id);
        MyOkHttp.getInstance().post(add_br, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String responseData = response.body().string();
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        showToast("提交成功");
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private synchronized void handleScanData(String scanResult) {

        scanResult = scanResult.trim();

        if ("".equals(scanResult)) {
            return;
        }

        //查出Asset中的assetNumber
//        String assetNumber = MyDataBase.init(this).assetDao().queryById(scanResult);

        //根据查出来的assetNumber查询出一条数据
        CheckData checkDataById = MyDataBase.init(this).checkDataDao().getCheckDataById(scanResult, odd.getText().toString());

        if (checkDataById == null) {
            com.assets.room.entity.Check allChecks = MyDataBase.init(Check.this).checkDao().getAllChecks(odd.getText().toString());
            Asset asset = MyDataBase.init(Check.this).assetDao().queryAllByNumber(scanResult);
            CheckData checkData = new CheckData();
            checkData.setCheckDataId(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(19)));
            checkData.setCheckId(allChecks.getCheckId());
            checkData.setCheckFlag(allChecks.getCheckFlag());
            checkData.setAssetNumber(asset.getAssetNumber());
            checkData.setAssetName(asset.getAssetName());
            checkData.setModel(asset.getModel());
            checkData.setType(asset.getType());
            checkData.setCheckResult("1");
            checkData.setPlace(asset.getPlace());
            checkData.setFlag("1");
            MyDataBase.init(Check.this).checkDataDao().insertCheckData(checkData);
        }

        Log.d(TAG, "checkDataById: " + checkDataById.toString());

        /**
         * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
         */

        if ("1".equals(checkDataById.getCheckResult()) || "0".equals(checkDataById.getCheckResult())) {
            showToast("此资产已盘点");
            return;
        }

        if ("3".equals(checkDataById.getCheckResult())) {
            MyDataBase.init(Check.this).checkDataDao().updateById("0", "1", scanResult, odd.getText().toString());
        }


        //正常数量
        int num1 = MyDataBase.init(this).checkDataDao().getCheckByResult("3",odd.getText().toString()).size();
        int num2 = MyDataBase.init(this).checkDataDao().getCheckByResult("0",odd.getText().toString()).size();
        int num3 = MyDataBase.init(this).checkDataDao().getCheckByResult("1",odd.getText().toString()).size();
        int num4 = MyDataBase.init(this).checkDataDao().getCheckByResult("2",odd.getText().toString()).size();

        For_inventory.setText(num1 + "");
        Have_inventory.setText(num2 + "");
        inventory_profit.setText(num3 + "");
        inventory_losses.setText(num4 + "");

        for (int i = 0; i < For_data.size(); i++) {
            Log.d(TAG, "For_data.get(i).getCode_number(): " + For_data.get(i).getCode_number());

            CheckData checkDataById1 = MyDataBase.init(this).checkDataDao().getCheckDataById(For_data.get(i).getCode_number(), odd.getText().toString());
            if (checkDataById1.getAssetNumber().equals(checkDataById.getAssetNumber())) {
                For_data.remove(i);
            }

        }

        runOnUiThread(() -> {
            dataList.clear();
            dataList.addAll(For_data);
            adapter.notifyDataSetChanged();
        });

//        int stutas = 0;
//        for (int i = 0; i < Have_data.size(); i++) {
//            if (scanResult.trim().equals(Have_data.get(i).getCode_number())) {
//                Toast.makeText(Check.this, "此资产已盘点", Toast.LENGTH_SHORT).show();
//                stutas = 1;
//                return;
//            }
//        }
//        //已盘点
//        for (int i = 0; i < profit_data.size(); i++) {
//            if (scanResult.trim().equals(profit_data.get(i).getCode_number())) {
//                stutas = 1;
//                Toast.makeText(Check.this, "此资产已盘点", Toast.LENGTH_SHORT).show();
//                return;
//            }
//        }
//        //待盘点
//        List<CheckData> assetCheckByStatus = MyDataBase.init(this).checkDataDao().getAssetCheckByStatus("3", Long.valueOf(odd.getText().toString()));
//        for (int i = 0; i < assetCheckByStatus.size(); i++) {
//            if (scanResult.trim().equals(For_data.get(i).getCode_number())) {
//                assetNumbers.add(For_data.get(i).getCode_number());
//                MyDataBase.init(this).checkDataDao().updateById("0", checkDataById.getAssetNumber(), odd.getText().toString());
////                Have_data.add(For_data.get(i));
////                stutas = 1;
//                For_data.remove(i);
//            }
//        }
//        //之前盘亏数据
//        for (int i = 0; i < losses_data.size(); i++) {
//            if (scanResult.trim().equals(losses_data.get(i).getCode_number())) {
//                assetNumbers.add(losses_data.get(i).getCode_number());
//                Have_data.add(losses_data.get(i));
//                stutas = 2;
//                losses_data.remove(i);
//            }
//        }
//
//        //正常数量
//        int num1 = MyDataBase.init(this).checkDataDao().getCheckByResult("3", odd.getText().toString()).size();
//        int num2 = MyDataBase.init(this).checkDataDao().getCheckByResult("0",odd.getText().toString()).size();
//        int num3 = MyDataBase.init(this).checkDataDao().getCheckByResult("1",odd.getText().toString()).size();
//        int num4 = MyDataBase.init(this).checkDataDao().getCheckByResult("2",odd.getText().toString()).size();
//
//        runOnUiThread(() -> {
//
//            For_inventory.setText(num1 + "");
//            Have_inventory.setText(num2 + "");
//            inventory_profit.setText(num3 + "");
//            inventory_losses.setText(num4 + "");
//
//        });


//        LogUtils.d(String.valueOf(stutas));
//        if (stutas == 0) {
//            stutas = 0;
//            query(scanResult.trim(), "");
//        } else {
//            runOnUiThread(() -> {
//                adapter.notifyDataSetChanged();
//                Have_inventory.setText(String.valueOf(Have_data.size()));
//                For_inventory.setText(String.valueOf(For_data.size()));
//                inventory_profit.setText(String.valueOf(profit_data.size()));
//                inventory_losses.setText(String.valueOf(losses_data.size()));
//            });
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


        Log.d(TAG, "keyCode: " +  keyCode + ",event: " + event.getKeyCode());
        return super.onKeyDown(keyCode, event);

    }

    private synchronized void handleRFIDData(String EPC) {
        Log.d(TAG, "EPC: " + EPC);
        LogUtils.d(EPC);
        /*switch (EPC) {
            case "E2801191A502006034EB6175":
                EPC = "2022030414330779";
                break;
            case "E28011700000020CE10085C7":
                EPC = "2022030414331040";
                break;
            case "A9E6202111100001":
                EPC = "2022030414331390";
                break;
            case "2022011215003753":
                EPC = "2022030414331644";
                break;
            case "E28011700000021502E4FAFF":
                EPC = "2022030414331931";
                break;
            case "E28011700000020CE10085C3":
                EPC = "2022030414292598";
                break;
            case "E28011700000020C15BE627D":
                EPC = "2022030414292818";
                break;
        }*/
        for (int i = 0; i < Have_data.size(); i++) {
            if (EPC.trim().equals(Have_data.get(i).getRfid())) {
                Toast.makeText(Check.this, "此资产已盘点", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //已盘点
        for (int i = 0; i < profit_data.size(); i++) {
            if (EPC.trim().equals(profit_data.get(i).getRfid())) {
                Toast.makeText(Check.this, "此资产已盘点", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        //待盘点
        for (int i = 0; i < For_data.size(); i++) {
            if (EPC.trim().equals(For_data.get(i).getRfid())) {
                // Input_item1 item1=new Input_item1(For_data.get(i).getAsset_img(),For_data.get(i).getAsset_name(),For_data.get(i).getSection(),For_data.get(i).getCode_number(),For_data.get(i).getCustodian(),For_data.get(i).getModel(),For_data.get(i).getCategory(),For_data.get(i).getRfid());
                assetNumbers.add(For_data.get(i).getRfid());
                Have_data.add(For_data.get(i));
                For_data.remove(i);
                int finalI = i;
                runOnUiThread(() -> {
                    if (star == 0) {
                        adapter.notifyItemRemoved(finalI);
                    } else if (star == 1) {
                        adapter.notifyItemInserted(adapter.getItemCount() - 1);
                    }
                    Have_inventory.setText(String.valueOf(Have_data.size()));
                    For_inventory.setText(String.valueOf(For_data.size()));
                    inventory_profit.setText(String.valueOf(profit_data.size()));
                    inventory_losses.setText(String.valueOf(losses_data.size()));
                });
                return;
            }
        }
        //之前盘亏数据
        for (int i = 0; i < losses_data.size(); i++) {
            if (EPC.trim().equals(losses_data.get(i).getRfid())) {
                assetNumbers.add(losses_data.get(i).getRfid());
                Have_data.add(losses_data.get(i));
                losses_data.remove(i);
                int finalI = i;
                runOnUiThread(() -> {
                    if (star == 3) {
                        adapter.notifyItemRemoved(finalI);
                    } else if (star == 1) {
                        adapter.notifyItemInserted(adapter.getItemCount() - 1);
                    }
                    Have_inventory.setText(String.valueOf(Have_data.size()));
                    For_inventory.setText(String.valueOf(For_data.size()));
                    inventory_profit.setText(String.valueOf(profit_data.size()));
                    inventory_losses.setText(String.valueOf(losses_data.size()));
                });
                return;
            }
        }
        query("", EPC.trim());
    }

    private synchronized void checkSelect() {

        //handler.post(runnable);
        /*handler.removeCallbacks(runnable);
        handler.postDelayed(runnable,500);*/
    }


    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();
    private long millis = 0;

    private void initRFID() {


        Button btn_rfid = findViewById(R.id.btn_rfid);
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {

                epc = epc.substring(0,16);
                Log.d(TAG, "epc这个卡是什么: " + epc);
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");

                //odd
                String asset_number = MyDataBase.init(this).assetDao().queryById(epc);
//                Log.d(TAG, "数据库中查到的asset_number: " + MyDataBase.init(this).assetDao().queryById(epc));
                CheckData checkDataById = MyDataBase.init(this).checkDataDao().getCheckDataById(asset_number, odd.getText().toString());
//                Log.d(TAG, "数据库中查到的checkData: " + checkDataById.toString());
                /**
                 * 盘点结果（0：正常，1：盘盈，2：盘亏 , 3:未盘)
                 */
                if (checkDataById == null) {
                    Asset asset = MyDataBase.init(this).assetDao().queryAllById(epc);
                    com.assets.room.entity.Check allChecks = MyDataBase.init(Check.this).checkDao().getAllChecks(odd.getText().toString());
//                    CheckData checkData = MyDataBase.init(this).checkDataDao().getAllCheckData(asset_number);
//                     public CheckData(Long checkDataId, Long checkId, Long checkFlag,
//                            String assetNumber, String assetName, String model,
//                            String type, String checkResult, String place,
//                            String isFlag) {
                    if (asset != null) {

                        MyDataBase.init(this).checkDataDao().insertCheckData(

                                //在checkData没有的去 Asset里面找 再添加进去 盘盈的数据
                                new CheckData(Long.valueOf(IdWorkerUtil.getInstance(1L).generateUniqueId(19)),allChecks.getCheckId(),allChecks.getCheckFlag(),asset.getAssetNumber(),asset.getAssetName(),asset.getModel(),asset.getType(),"1",asset.getPlace(),"1")

                        );

                        //正常数量
                        int num1 = MyDataBase.init(this).checkDataDao().getCheckByResult("3",odd.getText().toString()).size();
                        int num2 = MyDataBase.init(this).checkDataDao().getCheckByResult("0",odd.getText().toString()).size();
                        int num3 = MyDataBase.init(this).checkDataDao().getCheckByResult("1",odd.getText().toString()).size();
                        int num4 = MyDataBase.init(this).checkDataDao().getCheckByResult("2",odd.getText().toString()).size();

                        For_inventory.setText(num1 + "");
                        Have_inventory.setText(num2 + "");
                        inventory_profit.setText(num3 + "");
                        inventory_losses.setText(num4 + "");

                    }
                }
                if (checkDataById != null) {
                    MyDataBase.init(this).checkDataDao().updateById("0", "1", asset_number, odd.getText().toString());
                    MyDataBase.init(this).checkDao().updateStatus("1", odd.getText().toString());
                }

                for (int i = 0; i < For_data.size(); i++) {

                    CheckData checkDataById1 = MyDataBase.init(this).checkDataDao().getAssetCheckData(Long.valueOf(odd.getText().toString()));
                    if (checkDataById1.getAssetNumber().equals(checkDataById.getAssetNumber())) {
                        For_data.remove(i);
                    }

                }

                runOnUiThread(() -> {
                    dataList.clear();
                    dataList.addAll(For_data);
                    adapter.notifyDataSetChanged();



                });

                //正常数量
                int num1 = MyDataBase.init(this).checkDataDao().getCheckByResult("3",odd.getText().toString()).size();
                int num2 = MyDataBase.init(this).checkDataDao().getCheckByResult("0",odd.getText().toString()).size();
                int num3 = MyDataBase.init(this).checkDataDao().getCheckByResult("1",odd.getText().toString()).size();
                int num4 = MyDataBase.init(this).checkDataDao().getCheckByResult("2",odd.getText().toString()).size();

                For_inventory.setText(num1 + "");
                Have_inventory.setText(num2 + "");
                inventory_profit.setText(num3 + "");
                inventory_losses.setText(num4 + "");


                //以盘点
//                List<CheckData> checkByResult = MyDataBase.init(this)
//                        .checkDataDao().getCheckByResult("0");
//
//                //待盘点
//                List<CheckData> checkByResult2 = MyDataBase.init(this)
//                        .checkDataDao().getCheckByResult("3");
//
//                //1：盘盈
//                List<CheckData> checkByResult3 = MyDataBase.init(this)
//                        .checkDataDao().getCheckByResult("1");
//
//                //3:未盘
//                List<CheckData> checkByResult4 = MyDataBase.init(this)
//                        .checkDataDao().getCheckByResult("2");
//
//                for (int i = 0; i < checkByResult.size(); i++) {
////                    For_data.add(new Input_item1("", assetName,
////                            deptId, assetNumber, "", model, place,
////                            ""));
//                    Have_data.add(new Input_item1("", checkByResult.get(i).getAssetName(), deptId,
//                            checkByResult.get(i).getAssetNumber(), "", checkByResult.get(i).getModel(),
//                            checkByResult.get(i).getPlace(), ""));
//                }
//
//                for (int i = 0; i < checkByResult2.size(); i++) {
//                    For_data.add(new Input_item1("", checkByResult2.get(i).getAssetName(), deptId,
//                            checkByResult2.get(i).getAssetNumber(), "", checkByResult2.get(i).getModel(),
//                            checkByResult2.get(i).getPlace(), ""));
//                }
//
//                for (int i = 0; i < checkByResult3.size(); i++) {
//                    profit_data.add(new Input_item1("", checkByResult3.get(i).getAssetName(), deptId,
//                            checkByResult3.get(i).getAssetNumber(), "", checkByResult3.get(i).getModel(),
//                            checkByResult3.get(i).getPlace(), ""));
//                }
//
//                for (int i = 0; i < checkByResult4.size(); i++) {
//                    losses_data.add(new Input_item1("", checkByResult4.get(i).getAssetName(), deptId,
//                            checkByResult4.get(i).getAssetNumber(), "", checkByResult4.get(i).getModel(),
//                            checkByResult4.get(i).getPlace(), ""));
//                }

                Log.d(TAG, "循环Have_data: " + Have_data);

//                handleRFIDData(epc);
                //RFID(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });

        btn_rfid.setOnClickListener(v -> {
            Log.d(TAG, "点击读卡按钮 ==== ");
            long cs = System.currentTimeMillis() - millis;
            millis = System.currentTimeMillis();
            if (cs < 300) {
                return;
            }
            String rfidTitle = btn_rfid.getText().toString();
            LogUtils.d(rfidTitle);
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
    }
}
